import { ScrollView, View } from "@tarojs/components";
import Menu from "@/components/Menu/index";

import HeaderSearch from "@/components/HeaderSearch/index";
import Header from "@/components/Header/index";
import Footer from "@/components/Footer/index";
import GoodsTitle from "@/components/GoodsTitle/index";
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { requestPOST } from "@/request";
import {
  Button,
  Cell,
  Form,
  Popup,
  Input,
  Field,
  ConfigProvider,
  Picker,
  Toast,
  Dialog,
} from "@taroify/core";

export default function Index() {
  const [menu, setMenu] = useState<any>([]);
  const businessId = useSelector(
    (state: RootState) => state.business.businessId
  );
  const [open, setOpen] = useState(false);
  const [open1, setOpen1] = useState(false);
  const [open2, setOpen2] = useState(false);
  const [open3, setOpen3] = useState(false);
  const [form, setForm] = useState({
    categoryName: "",
    originalCategoryId: "",
  });
  const [form1, setForm1] = useState({
    pid: "",
    topName: "",
    categoryName: "",
    originalCategoryId: "",
  });
  const [categorys, setCategorys] = useState<any>([]);
  const [subCate, setSubCate] = useState<any>([]);

  const getMenu = () => {
    requestPOST(`shop/shopCategoryList/${businessId}`).then((res: any) => {
      let deep = 1;
      res.forEach((item) => {
        item.deep = deep;
        setChildrenDeep(item, deep);
      });
      console.log(res);
      setMenu([...res]);
    });
  };

  const setChildrenDeep = (data, deep) => {
    if (data.children && data.children.length) {
      ++deep;
      data.children.forEach((item) => {
        item.deep = deep;
        setChildrenDeep(item, deep);
      });
    }
  };

  const getCategorys = () => {
    requestPOST("shop/commonCategory").then((res: any) => {
      setCategorys(
        [...res].map((item) => ({
          ...item,
          label: item.categoryName,
          value: item.id,
        }))
      );
    });
  };

  const onSubmit = () => {
    if (!form.originalCategoryId) {
      return Toast.open({ type: "fail", message: "请选择分类名称" });
    }
    requestPOST("shop/shopAddCategory", {
      ...form,
      pid: 0,
      sort: 0,
    }).then(() => {
      Toast.open({ type: "success", message: "添加成功" });
      setOpen(false);
      setForm({
        categoryName: "",
        originalCategoryId: "",
      });
      formRef.current?.reset();
      getMenu();
    });
  };

  let children: any = [];

  const addMenu = (data) => {
    setForm1({ ...form1, topName: data.categoryName, pid: data.id });
    setOpen2(true);
    children = [];
    for (let i = 0; i < categorys.length; i++) {
      if (categorys[i].categoryName === data.categoryName) {
        children = categorys[i]?.children || [];
        break;
      }
      getCategoryNameChildren(categorys[i], data.categoryName);
    }

    children = children.map((item) => ({
      ...item,
      label: item.categoryName,
      value: item.id,
    }));
    setSubCate([...children]);
  };

  const getCategoryNameChildren = (data, categoryName) => {
    if (data.children && data.children.length) {
      let result = data.children;
      for (let i = 0; i < result.length; i++) {
        if (result[i].categoryName === categoryName) {
          children = result[i]?.children || [];
        }
        getCategoryNameChildren(result[i], categoryName);
      }
    }
  };

  const delMenu = (data) => {
    console.log(data);
    Dialog.confirm({
      title: "提示",
      message: "您确定要解绑吗？",
      onConfirm() {
        requestPOST(`shop/shopDelCategory/${data.id}`).then(() => {
          Toast.open({ type: "success", message: "删除成功" });
          getMenu();
        });
      },
    });
  };

  const onSubmit1 = () => {
    requestPOST("shop/shopAddCategory", { ...form1, sort: 0 }).then((res) => {
      Toast.open({ type: "success", message: "添加成功" });
      setOpen2(false);
      formRef1.current?.reset();
      setForm1({
        pid: "",
        topName: "",
        categoryName: "",
        originalCategoryId: "",
      });
      getMenu();
    });
  };

  useEffect(() => {
    getMenu();
    getCategorys();
  }, []);

  const formRef = useRef<any>();
  const formRef1 = useRef<any>();

  return (
    <View className="taroBox">
      <HeaderSearch />
      <Header />
      <View>
        <GoodsTitle title="产品分类" isMore={false} />
        <View style={{ padding: "14px 14px 0 14px" }}>
          <Button color="primary" size="small" onClick={() => setOpen(true)}>
            添加
          </Button>
        </View>
        <View style={{ margin: "20px 0" }}>
          <Menu
            data={menu}
            addMenu={(data) => addMenu(data)}
            delMenu={(data) => delMenu(data)}
          />
        </View>
      </View>
      <Footer />

      <Popup
        open={open}
        placement="center"
        style={{ height: "auto" }}
        rounded
        onClose={() => {
          setForm({
            categoryName: "",
            originalCategoryId: "",
          });
          setOpen(false);
        }}
        lock={false}
      >
        <View style={{ width: "90vw", padding: ".875rem", maxHeight: "90vh" }}>
          <Form ref={formRef} defaultValues={form} onSubmit={() => onSubmit()}>
            <Cell.Group inset style={{ margin: 0 }}>
              <Form.Item name="categoryName">
                <Form.Control>
                  <Field
                    label="分类名称"
                    name="categoryName"
                    clickable
                    isLink
                    style={{ padding: "0px" }}
                  >
                    <Input
                      value={form.categoryName}
                      readonly
                      placeholder="请选择分类名称"
                      onClick={() => setOpen1(true)}
                    />
                  </Field>
                </Form.Control>
              </Form.Item>
            </Cell.Group>
            <View
              style={{
                margin: "1rem",
                display: "flex",
                alignItems: "center",
                gap: "30px",
              }}
            >
              <Button shape="round" block color="primary" formType="submit">
                提交
              </Button>
            </View>
          </Form>
        </View>
      </Popup>

      <Popup
        open={open2}
        placement="center"
        style={{ height: "auto" }}
        rounded
        onClose={() => {
          setForm1({
            pid: "",
            topName: "",
            categoryName: "",
            originalCategoryId: "",
          });
          setOpen2(false);
        }}
        lock={false}
      >
        <View style={{ width: "90vw", padding: ".875rem" }}>
          <Form
            ref={formRef1}
            defaultValues={form1}
            onSubmit={() => onSubmit1()}
          >
            <Cell.Group inset style={{ margin: 0 }}>
              <Form.Item name="topName">
                <Form.Control>
                  <Field label="父级分类" style={{ padding: "0px" }}>
                    <Input value={form1.topName} readonly />
                  </Field>
                </Form.Control>
              </Form.Item>
              <Form.Item name="categoryName">
                <Form.Control>
                  <Field
                    label="分类名称"
                    name="categoryName"
                    clickable
                    isLink
                    style={{ padding: "0px" }}
                  >
                    <Input
                      value={form1.categoryName}
                      readonly
                      placeholder="请选择分类名称"
                      onClick={() => setOpen3(true)}
                    />
                  </Field>
                </Form.Control>
              </Form.Item>
            </Cell.Group>
            <View
              style={{
                margin: "1rem",
                display: "flex",
                alignItems: "center",
                gap: "30px",
              }}
            >
              <Button shape="round" block color="primary" formType="submit">
                提交
              </Button>
            </View>
          </Form>
        </View>
      </Popup>

      <ConfigProvider
        theme={{
          backdropZIndex: 1010,
        }}
      >
        <Popup
          open={open1}
          rounded
          placement="bottom"
          onClose={setOpen1}
          style={{ zIndex: 1011 }}
        >
          <Picker
            title="分类名称"
            columns={categorys}
            onCancel={() => setOpen1(false)}
            onConfirm={(newValue, obj) => {
              setForm({
                originalCategoryId: obj[0].value,
                categoryName: obj[0].label,
              });
              setOpen1(false);
            }}
          ></Picker>
        </Popup>
      </ConfigProvider>

      <ConfigProvider
        theme={{
          backdropZIndex: 1010,
        }}
      >
        <Popup
          open={open3}
          rounded
          placement="bottom"
          onClose={setOpen3}
          style={{ zIndex: 1011 }}
          lock={false}
        >
          <Picker
            title="分类名称"
            columns={subCate}
            onCancel={() => setOpen3(false)}
            onConfirm={(newValue, obj) => {
              setForm1({
                ...form1,
                originalCategoryId: obj[0].value,
                categoryName: obj[0].label,
              });
              setOpen3(false);
            }}
          ></Picker>
        </Popup>
      </ConfigProvider>
    </View>
  );
}
